<template>
  <div class="app-container">
    <!-- 留言输入区 -->
    <div class="message-input-card">
      <el-input
        type="textarea"
        placeholder="有什么心事想倾诉？在这里写下你的留言吧~"
        v-model="noteCont"
        :autosize="{ minRows: 4, maxRows: 6 }"
        maxlength="500"
        show-word-limit
        class="message-textarea"
      />
      <div class="submit-area">
        <el-button
          type="primary"
          @click="submit"
          :disabled="!noteCont.trim()"
          class="submit-btn"
        >
          提交留言
        </el-button>
      </div>
    </div>

    <!-- 温馨提示（仅我的留言页显示） -->
    <div class="tip-text" v-if="activeTab === 0">
      <i class="el-icon-info-circle"></i>
      温馨提示：匿名留言将不会显示个人信息，欢迎畅所欲言~
    </div>

    <!-- 标签页导航 -->
    <div class="tabs-container">
      <div class="tabs-header">
        <span
          class="tabs-nav"
          :class="{ 'tabs-nav-selected': activeTab === index }"
          v-for="(tab, index) in tabs"
          :key="index"
          @click="handleTabClick(index)"
        >
          {{ tab }}
        </span>
      </div>

      <!-- 标签页内容 -->
      <div class="tabs-content">
        <!-- 我的留言列表 -->
        <div v-show="activeTab === 0" class="message-list">
          <div
            class="message-item"
            v-for="(item, index) in messageList"
            :key="item.pnbId || index"
          >
            <!-- 留言内容 -->
            <div class="message-content">
              {{ item.noteCont }}
            </div>
            <div class="message-meta">
              <span class="create-time">{{ item.createTime }}</span>
            </div>

            <!-- 回复区域 -->
            <div class="reply-section" v-if="item.noteReply || item.replyCount > 0">
              <!-- 主回复展示 -->
              <div class="main-reply" v-if="item.noteReply && showReply">
                <div class="reply-content">
                  <span class="reply-author">{{ item.noteReply.createBy }}</span>
                  <span class="reply-separator">回复@{{ item.noteReply.replyPerson }}</span>
                 ：
                  <span class="reply-text">{{ item.noteReply.replyCont }}</span>
                </div>
                <div class="reply-meta">
                  <span 
                    class="reply-count" 
                    @click="toggleReplyList(item.pnbId)"
                  >
                    {{ repliesList.length > 0 ? '收起回复' : `共${item.replyCount}条回复` }}▼
                  </span>
                  <span class="reply-time">{{ item.noteReply.createTime }}</span>
                </div>
              </div>

              <!-- 回复列表（点击展开/收起） -->
              <div class="reply-list" v-if="repliesList.length > 0 && !showReply">
                <div
                  class="reply-item"
                  v-for="(reply, rIndex) in repliesList"
                  :key="reply.pnrId || rIndex"
                  @mouseenter="showReplyActions(rIndex)"
                  @mouseleave="hideReplyActions()"
                >
                  <div class="reply-content">
                    <span class="reply-author">{{ reply.createBy }}</span>
                    <span class="reply-separator">回复</span>
                    <span class="reply-target">{{ reply.replyPerson }}</span>：
                    <span class="reply-text">{{ reply.replyCont }}</span>
                  </div>
                  <div class="reply-meta">
                    <span class="reply-time">{{ reply.createTime }}</span>
                    
                    <!-- 回复操作按钮（悬停显示） -->
                    <div class="reply-actions" v-show="hoveredReplyIndex === rIndex">
                      <el-button 
                        type="text" 
                        size="mini" 
                        class="action-btn delete-btn"
                        @click="handleDeleteReply(reply)"
                      >
                        <i class="fa fa-trash"></i> 删除
                      </el-button>
                      <el-button 
                        type="text" 
                        size="mini" 
                        class="action-btn reply-btn"
                        @click="openReplyDialog(reply)"
                      >
                        <i class="fa fa-reply"></i> 回复
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态提示 -->
          <div class="empty-state" v-if="messageList.length === 0">
            <el-empty description="暂无留言，快去写下你的第一条留言吧~"></el-empty>
          </div>
        </div>
      </div>
    </div>

    <!-- 回复弹窗 -->
    <el-dialog 
      title="回复留言" 
      :visible.sync="openReply" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" ref="replyForm" label-width="80px">
        <el-form-item 
          label="回复内容" 
          prop="replyCont"
          :rules="[{ required: true, message: '请输入回复内容', trigger: 'blur' }]"
        >
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            v-model="form.replyCont"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openReply = false">取消</el-button>
        <el-button type="primary" @click="submitReply">确认回复</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { stulist, noteboard, getReplies, parentReplies, delReply } from "@/api/psychological/message";

export default {
  name: "StudentMessageBoard",
  data() {
    return {
      // 标签页状态
      activeTab: 0,
      tabs: ["我的留言"], // 标签页名称

      // 留言内容
      noteCont: "",

      // 留言列表数据
      messageList: [],

      // 回复相关
      repliesList: [], // 回复列表
      openReply: false, // 回复弹窗开关
      form: { replyCont: "" }, // 回复表单
      parentReplyId: "", // 被回复的回复ID
      currentMessageId: "", // 当前操作的留言ID

      // 交互状态
      hoveredReplyIndex: null, // 悬停的回复索引
      showReply: true, // 控制回复展示状态
    };
  },

  created() {
    this.getMyMessages(); // 初始化加载我的留言
  },

  methods: {
    /** 加载我的留言列表 */
    getMyMessages() {
      stulist({ type: "W" }).then((res) => {
        this.messageList = res.rows || [];
      }).catch(err => {
        this.$message.error("加载留言失败，请稍后重试");
        console.error("留言加载错误:", err);
      });
    },

    /** 标签页切换 */
    handleTabClick(index) {
      if (this.activeTab === index) return;
      this.activeTab = index;
      this.getMyMessages(); // 切换标签页时刷新数据
    },

    /** 提交新留言 */
    submit() {
      if (!this.noteCont.trim()) {
        this.$message.warning("请输入留言内容");
        return;
      }

      noteboard({ noteCont: this.noteCont }).then((res) => {
        if (res.code === 200) {
          this.$message.success("留言提交成功");
          this.noteCont = ""; // 清空输入框
          this.getMyMessages(); // 刷新留言列表
        } else {
          this.$message.error(res.msg || "留言提交失败");
        }
      }).catch(err => {
        this.$message.error("提交失败，请稍后重试");
        console.error("留言提交错误:", err);
      });
    },

    /** 切换回复列表展示/隐藏 */
    toggleReplyList(messageId) {
      this.currentMessageId = messageId;
      this.showReply = !this.showReply;

      // 加载回复列表
      if (!this.showReply) {
        getReplies(messageId).then((res) => {
          this.repliesList = res.data || [];
        }).catch(err => {
          this.$message.error("加载回复失败");
          console.error("回复加载错误:", err);
        });
      }
    },

    /** 打开回复弹窗 */
    openReplyDialog(reply) {
      this.openReply = true;
      this.parentReplyId = reply.pnrId; // 记录被回复的回复ID
      this.form.replyCont = ""; // 清空回复内容
      this.$nextTick(() => {
        this.$refs.replyForm.clearValidate(); // 清除表单验证
      });
    },

    /** 提交回复 */
    submitReply() {
      this.$refs.replyForm.validate((valid) => {
        if (valid) {
          parentReplies(this.parentReplyId, this.form).then((res) => {
            if (res.code === 200) {
              this.$message.success("回复成功");
              this.openReply = false;
              this.toggleReplyList(this.currentMessageId); // 刷新回复列表
            } else {
              this.$message.error(res.msg || "回复失败");
            }
          }).catch(err => {
            this.$message.error("回复提交失败");
            console.error("回复提交错误:", err);
          });
        }
      });
    },

    /** 显示回复操作按钮 */
    showReplyActions(index) {
      this.hoveredReplyIndex = index;
    },

    /** 隐藏回复操作按钮 */
    hideReplyActions() {
      this.hoveredReplyIndex = null;
    },

    /** 删除回复 */
    handleDeleteReply(reply) {
      this.$confirm("确定要删除这条回复吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delReply(reply.pnrId).then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.toggleReplyList(this.currentMessageId); // 刷新回复列表
          } else {
            this.$message.error(res.msg || "删除失败");
          }
        }).catch(err => {
          this.$message.error("删除失败");
          console.error("回复删除错误:", err);
        });
      });
    },
  },
};
</script>

<style scoped>
/* 容器样式 */
.app-container {
  padding: 20px;
 
  margin: 0 auto;
}

/* 留言输入区 */
.message-input-card {
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.message-textarea {
  width: 100%;
  border-radius: 4px;
}

.submit-area {
  text-align: right;
  margin-top: 10px;
}

.submit-btn {
  padding: 8px 20px;
}

/* 温馨提示 */
.tip-text {
  color: #666;
  font-size: 13px;
  padding: 10px 15px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.tip-text i {
  margin-right: 5px;
  color: #409eff;
}

/* 标签页样式 */
.tabs-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.tabs-header {
  display: flex;
  border-bottom: 1px solid #eaecef;
  padding-left: 15px;
}

.tabs-nav {
  padding: 12px 20px;
  margin-right: 10px;
  cursor: pointer;
  font-size: 14px;
  position: relative;
  transition: color 0.3s;
}

.tabs-nav:hover {
  color: #409eff;
}

.tabs-nav-selected {
  color: #409eff;
  font-weight: 500;
}

.tabs-nav-selected::after {
  content: "";
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #409eff;
}

.tabs-content {
  padding: 15px;
}

/* 留言列表样式 */
.message-list {
  margin-top: 10px;
}

.message-item {
  padding: 15px;
  border-bottom: 1px solid #f0f2f5;
  transition: background 0.2s;
}

.message-item:last-child {
  border-bottom: none;
}

.message-item:hover {
  background: #fafafa;
}

.message-content {
  color: #333;
  line-height: 1.6;
  margin-bottom: 10px;
  font-size: 14px;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.create-time {
  color: #999;
  font-size: 12px;
}

/* 回复区域样式 */
.reply-section {
  margin-top: 15px;
  padding-left: 15px;
  border-left: 2px solid #eaecef;
}

.main-reply {
  margin-bottom: 10px;
}

.reply-list {
  margin-top: 10px;
}

.reply-item {
  padding: 10px 0;
  border-bottom: 1px dashed #f0f2f5;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-content {
  display: flex;
  flex-wrap: wrap;
  font-size: 14px;
}

.reply-author {
  color: #2d8cf0;
  font-weight: 500;
  margin-right: 5px;
}

.reply-target {
  color: #f56c6c;
  margin-right: 5px;
}

.reply-separator {
  color: #999;
  margin: 0 5px;
}

.reply-text {
  color: #333;
  flex: 1;
}

.reply-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
  font-size: 12px;
}

.reply-time {
  color: #999;
}

.reply-count {
  color: #409eff;
  cursor: pointer;
  margin-right: 10px;
}

/* 回复操作按钮 */
.reply-actions {
  display: inline-flex;
  align-items: center;
}

.action-btn {
  padding: 0 5px !important;
  margin-left: 5px !important;
  font-size: 12px !important;
}

.delete-btn {
  color: #f56c6c !important;
}

.reply-btn {
  color: #409eff !important;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .tabs-nav {
    padding: 10px 15px;
    font-size: 13px;
  }

  .message-item {
    padding: 12px 10px;
  }

  .reply-section {
    padding-left: 10px;
  }
}
</style>